package fr.epsi.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import fr.epsi.model.Brand;

@Transactional
public class BrandServiceImpl implements BrandService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<Brand> findAll() {
        Query query = getEntityManager().createQuery("select b from Brand b");
        return query.getResultList();
    }

    public void save(Brand brand) {
        if (brand.getId() == null) {
            em.persist(brand);
        } else {
            em.merge(brand);
        }
    }

    public void remove(int id) {
        Brand brand = find(id);
        if (brand != null) {
            em.remove(brand);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public Brand find(int id) {
        return em.find(Brand.class, id);
    }

}
